# SerendipityImporter plugin for Movable Type
# Author: Robert Bohne
#
# $Id: Import.pm 7 2008-10-06 12:21:21Z Robert.Bohne $
package SerendipityImporter::Import;
use strict;
use Data::Dumper;
use Date::Parse;
use SerendipityImporter::RssReader;
use base qw(MT::ErrorHandler);

our $self = {};

sub import_contents {
    shift;
    my %param = @_;
	my $iter = $param{Iter};	
	$self->{_callback} = $param{Callback} || sub { };
	
	$self->{_callback}->(MT->translate("Read RSS Feed from [_1]...\n", $param{s9y_url}));
	
	$self->{_rss} = new SerendipityImporter::RssReader({url => $param{s9y_url},proxy_server => $param{proxy_server} }) or return __PACKAGE__->error(MT->translate("Error loading the RSS feed."));;
	
	if (defined $param{Blog}){
		$self->{_blog} = $param{Blog}
	}else{
		return __PACKAGE__->error(MT->translate("No Blog"));
	}
	
	

   
    if ($self->{_author} = $param{ImportAs}) {
#        $self->{_callback}->("Importing entries as user '", $author->name, "'\n");
    } elsif ($self->{_parent_author} = $param{ParentAuthor}) {
        require MT::Auth;
		$self->{_createAuthor} = 1;
		$self->{_defaultAuthorPassword} = $param{NewAuthorPassword}
            or return __PACKAGE__->error(MT->translate(
                "You need to provide a password if you are going to " .
                "create new users for each user listed in your blog."))
               if (MT::Auth->password_exists);
    } else {
        return __PACKAGE__->error(MT->translate("Need either ImportAs or ParentAuthor"));
    }
    $self->{_callback}->("\n");
	require MT::Category;
	require MT::Author;
	require MT::Entry;
	require MT::Placement;
	require MT::Comment;
	
	foreach my $val (@{$self->{_rss}->getAllEntries}){
		
		# $VAR1 = '_content';
		# $VAR2 = '_author';
		# $VAR3 = '_pubDate';
		# $VAR4 = '_title';
		# $VAR5 = '_categories';
		# $VAR6 = '_comments';
		
		my $entry = MT::Entry->new;
		$entry->blog_id($self->{_blog}->id);
        $entry->status($self->{_blog}->status_default);
        $entry->allow_comments($self->{_blog}->allow_comments_default);
		$entry->allow_pings($self->{_blog}->allow_pings_default ? 1 : 0);
        $entry->convert_breaks($self->{_blog}->convert_paras);
        $entry->author_id(getAuthor($self,$val->{_author})->id);
		
		$entry->title($val->{_title});
		
		my ($ss,$mm,$hh,$day,$month,$year,$zone) = strptime($val->{_pubDate});
		$year  = ($year+1900);
		$month = ($month+1);
		$entry->authored_on(sprintf "%04d%02d%02d%02d%02d%02d", $year, $month, $day, $hh, $mm, $ss);
		
		$entry->status(MT::Entry::RELEASE);
		$entry->text($val->{_content});
		
		
		# save the entry.
       	$self->{_callback}->(MT->translate("Saving entry ('[_1]')...", MT::I18N::utf8_off($entry->title)));
		if ($entry->save) {
			$self->{_callback}->(MT->translate("ok (ID [_1])", $entry->id) . "\n");
		} else {
			$self->{_callback}->(MT->translate("failed") . "\n");
			die MT->translate("Save failed: [_1]", $entry->errstr);
		}

		#
		# Placement
		#
		foreach my $cat ( @{$val->{_categories}}){
			my $place = MT::Placement->new;
	        $place->is_primary(0);
	        $place->entry_id($entry->id);
	        $place->blog_id($self->{_blog}->id);
	        $place->category_id(getCategory($self,$cat,getAuthor($self,$val->{_author})->id)->id);
	        $place->save or die MT->translate("Saving placement failed: [_1]", $place->errstr);
		}
		
		#
		# Comments
		#
		foreach my $comment (@{$val->{_comments}}){
			# $VAR1 = '_content';
			# $VAR2 = '_author';
			# $VAR3 = '_pubDate';
			my $cmt = MT::Comment->new or return("Couldn't construct MT::Comment " . MT::Comment->errstr);;
			$cmt->blog_id($self->{_blog}->id);
			$cmt->entry_id($entry->id);
			$cmt->approve;
			$cmt->author($comment->{_author});
			
			my ($ss,$mm,$hh,$day,$month,$year,$zone) = strptime($comment->{_pubDate});
			$year  = ($year+1900);
			$month = ($month+1);
			$cmt->created_on(sprintf "%04d%02d%02d%02d%02d%02d", $year, $month, $day, $hh, $mm, $ss);
			
			$cmt->text($comment->{_content});
			

	        $self->{_callback}->(MT->translate("Creating new comment (from '[_1]')...", $cmt->author));
	        if ($cmt->save) {
	            $self->{_callback}->(MT->translate("ok (ID [_1])", $cmt->id) . "\n");
	        } else {
	            $self->{_callback}->(MT->translate("failed") . "\n");
	            die MT->translate("Saving comment failed: [_1]", $cmt->errstr);
	        }
		}
		
	}

    return 1;
}





sub getCategory{
=head1 getCategory
	return MT::Category
=cut
	my $self = shift;
	my ($name,$author_id) = @_;
	
    my $cat = MT::Category->load({ label => $name,blog_id => $self->{_blog}->id });
    unless ($cat) {
        $cat = MT::Category->new;
        $cat->blog_id($self->{_blog}->id);
        $cat->label($name);
        $cat->author_id($author_id);
        $cat->parent(0);
        $self->{_callback}->(MT->translate("Creating new category ('[_1]')...", $name));
        if ($cat->save) {
            $self->{_callback}->(MT->translate("ok") . "\n");
        } else {
            $self->{_callback}->(MT->translate("failed") . "\n");
            return __PACKAGE__->error(MT->translate(
             "Saving category failed: [_1]", $cat->errstr));
        }
    }
  
	return $cat;
}

sub getAuthor{
	my $self = shift;
	my ($name) = @_;
	

	if (defined $self->{_createAuthor}){
		unless (defined $self->{_authorsMap}->{$name}){
			$self->{_authorsMap}->{$name} = $self->createAuthor($name);
		}
		return $self->{_authorsMap}->{$name};
	}else{
		return $self->{_author};
	}
	return 0;
}



sub createAuthor{
=head1 createAuthor
	create new author
	
	return MT::Author
	
=cut	
	my $self = shift;
	my ($name) = @_;
	
	my $author;
	$self->{_callback}->(MT->translate("Creating new user ('[_1]')...", $name));
	$author = MT::Author->new;
   	$author->created_by($self->{_parent_author}->id);
   	$author->name($name);
   	$author->email('');
   	$author->type(MT::Author::AUTHOR);
    $author->auth_type(MT->config->AuthenticationModule);
   	if (defined $self->{_defaultAuthorPassword}) {
      	$author->set_password($self->{_defaultAuthorPassword});
   	} else {
       	$author->password('(none)');
   	}
   	if ($author->save) {
       	$self->{_callback}->(MT->translate("ok") . "\n");
   	} else {
       	$self->{_callback}->(MT->translate("failed") . "\n");
       	return __PACKAGE__->error(MT->translate(
           	"Saving user failed: [_1]", $author->errstr));
   	}

	return $author;
}


sub get_param {
    my $class = shift;
    my ($blog_id) = @_;

    my $param = { blog_id => $blog_id };
    $param;
}






1;

__END__
